package com.hailiao.devicebasicsdkdemo.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.clj.fastble.data.BleDevice
import com.hailiao.devicebasicsdkdemo.R
import com.hailiao.devicebasicsdkdemo.databinding.ItemDeviceBleBinding

/**
 * 扫描设备适配器
 *
 * Author: D10NG
 * Time: 2020/12/4 5:46 下午
 */
class DeviceBleAdapter constructor(
    val mList: MutableList<BleDevice> = mutableListOf()
): RecyclerView.Adapter<DeviceBleAdapter.ViewHolder>() {

    private var listener: RecyclerViewClick? = null

    /** 设置点击监听器 */
    fun setListener(listener: (RecyclerViewClick.() -> Unit)) {
        val viewClick = RecyclerViewClick()
        viewClick.listener()
        this.listener = viewClick
    }

    /**
     * 更新列表
     * @param list List<BleDevice>
     */
    fun update(list: List<BleDevice>) {
        mList.clear()
        mList.addAll(list)
        notifyDataSetChanged()
    }

    class ViewHolder constructor(
        val binding: ItemDeviceBleBinding
    ): RecyclerView.ViewHolder(binding.root) {

        fun bind(bleDevice: BleDevice) {
            binding.deviceName = bleDevice.name
            binding.deviceMac = bleDevice.mac
            binding.executePendingBindings()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding: ItemDeviceBleBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_device_ble,
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = mList[position]
        holder.bind(item)

        holder.binding.ctlItem.setOnClickListener {
            this.listener?.click(it, position, item)
        }
    }

    override fun getItemCount(): Int = mList.size
}